package com.kstech.ks_gaz01.fragments


import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.chad.library.adapter4.layoutmanager.QuickGridLayoutManager
import com.google.android.material.tabs.TabLayout
import com.kstech.ks_gaz01.XML_REALTIME
import com.kstech.ks_gaz01.data.DebugDataBean
import com.kstech.ks_gaz01.data.GridSpaceItemDecoration
import com.kstech.ks_gaz01.databinding.FragmentRealtimeparaBinding
import com.kstech.ks_gaz01.fragments.RealTimePartFragment.Companion.addReadyList
import com.kstech.ks_gaz01.realTime.ChildFragment
import com.kstech.ks_gaz01.realTime.RealTimeAdapter
import com.kstech.ks_gaz01.socket.SocketManagerNew

/**
 * author: blankii
 * created on: 2024/5/8 11:16
 * description: 实时参数界面，有的车型不带下边栏
 */
class RealTimeParaFragment : ChildFragment() {
    private var _binding: FragmentRealtimeparaBinding? = null

    // 只能在onCreateView与onDestroyView之间的生命周期里使用
    private val binding: FragmentRealtimeparaBinding get() = _binding!!

    /**
     * 点击的实时参数
     */
    private lateinit var realTimeAdapter: RealTimeAdapter
    private var realTimeList = ArrayList<DebugDataBean.Item>()//发送的列表
    private var realTimeShowList = ArrayList<DebugDataBean.Item>()//显示的列表 带着bit位数据

    /**
     * 点击序号
     */
    private var lastParentTabPosition = 0
    private var lastChildTabPosition = 0
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        _binding = FragmentRealtimeparaBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        //在parentTabs监听事件注册好之后再选中
        binding.parentTabLayout.getTabAt(0)!!.select()
    }


    private fun reloadRealTimeList() {
        /**
         * 装载realTimeShowList 加载adapter用
         */
        realTimeShowList.clear()
        realTimeList.forEach {
            if (it.isBitArrayInitialized() && it.bitArray.size > 0) {
                for (i in it.bitArray.indices) {
                    val bit = it.bitArray[i]
                    realTimeShowList.add(
                        DebugDataBean.Item(
                            it.para0 + "_$i", bit, it.para5, it.isNegativeNumber, i, "00"
                        )
                    )
                }
            } else {
                realTimeShowList.add(it)
            }
        }


        realTimeAdapter.notifyDataSetChanged()
    }

    private var currentGroupAddress = ""
    private fun sendLooperRealTime() {
        if (realTimeList.size <= 0) {
            return
        }
        currentGroupAddress = (realTimeList[0].para0.toInt() - 1).toString()
        addReadyList(
            true, arrayListOf(
                SocketManagerNew.ReadBean(
                    currentGroupAddress, realTimeList[0].para2, realTimeList.size
                )
            )
        )
    }


    private fun initView() {

        binding.apply {
            /**
             * 加载 itemAdapter
             */
            realTimeRecyclerView.layoutManager = QuickGridLayoutManager(requireActivity(), 5)
            realTimeRecyclerView.addItemDecoration(GridSpaceItemDecoration( 10, 10))
            realTimeAdapter = RealTimeAdapter()
            realTimeAdapter.submitList(realTimeShowList)
            binding.realTimeRecyclerView.adapter = realTimeAdapter
            /**
             * parentTabs 以及绑定事件监听
             */
            val parentList = DebugDataBean.xmlMap[XML_REALTIME]
            parentList!!.forEach {
                parentTabLayout.addTab(parentTabLayout.newTab().setText(it.name), false)
            }

            parentTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    lastParentTabPosition = tab!!.position
                    /**
                     * 加载tabs-child
                     */
                    binding.childTabLayout.removeAllTabs()
                    val parent = DebugDataBean.xmlMap[XML_REALTIME]!![lastParentTabPosition]
                    if (!parent.isExistedChildTab) {
                        binding.childTabLayout.visibility = View.GONE
                        realTimeList.clear()
                        realTimeList.addAll(parent.itemList)
                        reloadRealTimeList()
                        sendLooperRealTime()
                    } else {
                        binding.childTabLayout.visibility = View.VISIBLE
                        parent.childList.forEach {
                            binding.childTabLayout.addTab(
                                binding.childTabLayout.newTab().setText(it.name), false
                            )
                        }
                        binding.childTabLayout.getTabAt(0)!!.select()
                    }
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {

                }

                override fun onTabReselected(tab: TabLayout.Tab?) {

                }

            })

            /**
             * childTabs 绑定事件监听
             */
            childTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    lastChildTabPosition = tab!!.position

                    realTimeList.clear()
                    val parent = parentList!![lastParentTabPosition]
                    realTimeList.addAll(parent.childList[lastChildTabPosition].itemList)
                    reloadRealTimeList()
                    /**
                     * 加入循环消息队列
                     */
                    sendLooperRealTime()
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {

                }

                override fun onTabReselected(tab: TabLayout.Tab?) {

                }
            })

        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun writeSuccess(address: String, value: String) {

    }

    /**
     * @param address 发送的address 地址
     * @param result 处理成十六进制的字符串数据
     */
    override fun readSuccess(address: String, result: ArrayList<String>) {
        if (realTimeList.size <= 0) {
            return
        }
        if (address == (realTimeList[0].para0.toInt() - 1).toString()) {
            val valueList = ArrayList<String>()
            for (i in realTimeList.indices) {
                if (realTimeList[i].isBitArrayInitialized() && realTimeList[i].bitArray.size > 0) {
                    for (j in realTimeList[i].bitArray.indices) {
                        valueList.add(result[i])
                    }
                } else {
                    valueList.add(result[i])
                }
            }
            for (i in realTimeShowList.indices) {
                realTimeShowList[i].revData = valueList[i]
            }
            realTimeAdapter.notifyDataSetChanged()
        }
    }

    override fun pageOnResume() {/*
        * 加入循环消息队列
        */
        sendLooperRealTime()
    }

    override fun pageOnPause() {

    }
}